const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()

exports.main = async (event, context) => {
  const openid = event.openid

  // 1. 查出当前用户所有持仓股票代码
  const selfPositions = await db.collection('positions').where({ openid }).get()
  const ownCodes = selfPositions.data.map(x => x.code)

  if (!ownCodes.length) return { result: [] }

  // 2. 查找“其他用户持有这些股票”的所有记录
  const others = await db.collection('positions').where({
    code: db.command.in(ownCodes),
    openid: db.command.neq(openid)
  }).get()

  // 3. 统计这些用户还买过什么股票（排除当前用户已持有的）
  const freqMap = {}
  for (let item of others.data) {
    // 当前用户未持有且不是自己的记录才计数
    if (!ownCodes.includes(item.code)) {
      freqMap[item.code] = (freqMap[item.code] || 0) + 1
    }
  }

  // 4. 排序取前5
  const recommendCodes = Object.entries(freqMap)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 5)
    .map(x => x[0])

  if (!recommendCodes.length) return { result: [] }

  // 5. 查这些股票的具体信息
  const recommendStocksRes = await db.collection('allStocks').where({
    code: db.command.in(recommendCodes)
  }).get()

  // 6. 返回推荐股票
  return { result: recommendStocksRes.data }
}
